package com.cn.demo4.servlet.admin.nav;

import com.alibaba.fastjson.JSONObject;
import com.cn.demo4.model.NavModel;
import com.cn.demo4.service.INavService;
import com.cn.demo4.service.impl.NavServiceImpl;
import com.cn.demo4.util.LoadImg;
import com.cn.demo4.util.Tool;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/adminFile/nav/update")
public class NavEditServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.解决乱码问题
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");

        //2.取得前台传递的值
        LoadImg.loadImg(req);
        /**
         * req在文件流的时候只能拿到一次数据，所以也不能进入过滤器
         */
        //如果没有登录则直接返回resp.getWriter().println(jsonObject);
        HttpSession session = req.getSession();
        String key = (String) req.getAttribute("loginPhone");
        String phone = (String) session.getAttribute(key);
        if (phone == null) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("result", "noLogin");
            resp.getWriter().println(jsonObject);
            return;
        }

        //封装数据
        NavModel navModel = new NavModel();
        navModel.setId(Tool.stringToInt((String) req.getAttribute("id")));
        navModel.setName((String) req.getAttribute("name"));
        navModel.setHref((String) req.getAttribute("href"));
        navModel.setStatus(Tool.stringToInt((String) req.getAttribute("status")));
        navModel.setTypeId(Tool.stringToInt((String) req.getAttribute("typeId")));
        navModel.setImg((String) req.getAttribute("img"));
        navModel.setContent((String) req.getAttribute("content"));

        //调用服务层
        INavService iNavService = new NavServiceImpl();
        //得到结果
        String result = iNavService.update(navModel);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("result",result);
        resp.getWriter().println(jsonObject);
    }
}
